package com.mall.alipay.controller;

import com.mall.alipay.common.R;
import com.mall.alipay.common.ResultCodeEnum;
import com.mall.alipay.mapper.GoodsMapper;
import com.mall.alipay.mapper.OrdersMapper;
import com.mall.alipay.entity.Goods;
import com.mall.alipay.entity.Orders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/good")
public class GoodsController {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private OrdersMapper ordersMapper;

    /**
     * 商品列表
     * @return
     */
    @GetMapping("/goods")
    public R getGoods() {
        return R.setResult(ResultCodeEnum.SUCCESS).data(goodsMapper.selectList(null));
    }

    @Transactional
    @PostMapping("/buy")
    public R buy(@RequestParam Integer goodsId) {
        Goods goods = goodsMapper.selectById(goodsId);
        int store = goods.getStore() - 1;
        if (store < 0) {
            return R.setResult(ResultCodeEnum.GOODS_OUT_OF_STOCK);
        }
        Date date = new Date();
        Orders orders = new Orders();
        orders.setGoodsId(goodsId);
        orders.setCreateTime(date);
        orders.setName("购买" + goods.getName() + "订单");
        orders.setOrderId(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis());
        orders.setTotal(goods.getPrice().multiply(BigDecimal.ONE));

        goods.setStore(store);
        ordersMapper.insert(orders);
        goodsMapper.updateById(goods);
        return R.ok();
    }
}
